

import os
import logging
import datetime
import requests
from settings import *
from .wx_user_table_methods import WxUserTableMethods

logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

'''-- 微信小程序access_token表
CREATE TABLE IF NOT EXISTS wx_access_token (
    id SERIAL PRIMARY KEY, -- 微信小程序access_token ID，唯一标识每个access_token
    access_token VARCHAR(50) PRIMARY KEY, -- 微信小程序access_token
    expires_in INT NOT NULL, -- access_token有效期
    expire_time TIMESTAMP NOT NULL -- access_token过期时间
);'''

# 设置静态资源存储目录
UPLOAD_FOLDER = 'upload'
if not os.path.exists(UPLOAD_FOLDER):
    os.makedirs(UPLOAD_FOLDER)

class WxAccessTokenTableMethods: 

    def __init__(self, conn, cur):
        self.cursor = cur
        self.conn = conn

    def get_access_token_by_api(self):

        url = "https://api.weixin.qq.com/cgi-bin/token"

        params = {
            "grant_type": "client_credential",
            "appid": WX_APP_ID,
            "secret": WX_APP_SECRET
        }

        r = requests.get(url, params=params)

        if r.status_code == 200:
            data = r.json()
            access_token = data.get("access_token")
            expires_in = data.get("expires_in")
            if access_token and expires_in:
                return access_token, expires_in
            else:
                logger.error("Error getting access token from WeChat API")
                return None, None
        else:
            logger.error("Error getting access token from WeChat API")
            return None, None
        
    def insert_access_token(self, access_token, expires_in):

        expires_time = datetime.datetime.now() + datetime.timedelta(seconds=expires_in-100)  # 减去100秒，防止过期时间太短导致无法获取access_token

        sql = """INSERT INTO wx_access_token (access_token, expires_in, expire_time) VALUES (%s, %s, %s)"""
        values = (access_token, expires_in, expires_time)

        self.cursor.execute(sql, values)
        self.conn.commit()

    def get_access_token(self):

        sql = """SELECT access_token FROM wx_access_token WHERE expire_time > NOW() ORDER BY expire_time DESC LIMIT 1"""

        self.cursor.execute(sql)
        result = self.cursor.fetchone()

        if result:
            return result["access_token"]
        
        else:
            
            access_token, expires_in = self.get_access_token_by_api()

            if access_token and expires_in:

                self.insert_access_token(access_token, expires_in)

                return access_token
            
            else:
                logger.error("Error getting access token from database or WeChat API")
                return None
            
    def get_user_phone_number(self, code, openid):

        access_token = self.get_access_token()

        url = f"https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token={access_token}"

        data = {
            "code": code,
            "openid": openid
        }
        print(f"sending request data: {data}")

        r = requests.post(url, json=data)

        # {'errcode': 0, 'errmsg': 'ok', 'phone_info': {'phoneNumber': '18566759511', 'purePhoneNumber': '18566759511', 'countryCode': '86', 'watermark': {'timestamp': 1717595317, 'appid': 'wxebac0602f61673f0'}}}

        if r.status_code == 200:
            data = r.json()
            print(data)
            if data.get("errcode") == 0:

                phone_number = data["phone_info"]["purePhoneNumber"]

                # 保存用户信息到数据库

                WxUserTableMethods(self.conn, self.cursor).update_user_phone_number(openid, phone_number)

                return phone_number
            else:
                logger.error(f"Error getting user phone number: {data.get('errmsg')}")
                return None
            
        else:
            logger.error("Error getting user phone number from WeChat API")
            return None
    # 获取小程序码的功能
    def get_wxa_code(self, path="pages/index/index", env_version="trial", params={}, filename="code.png"):
        '''
        '''
        filename = os.path.join(UPLOAD_FOLDER, filename)

        params_str = "&".join([f"{k}={v}" for k, v in params.items()])

        access_token = self.get_access_token()

        url = f"https://api.weixin.qq.com/wxa/getwxacode?access_token={access_token}"

        data = {
            "path": f"{path}?{params_str}",
            "env_version": env_version,
        }

        r = requests.post(url, json=data)

        if r.status_code != 200:
            logger.error("Error getting wxa code from WeChat API")
            logger.error(f"response content: {r.status_code}")
            return False
        
        # 如果返回的的不是一个buffer，说明获取失败
        if not isinstance(r.content, bytes):

            logger.error("Error getting wxa code from WeChat API")
            logger.error(f"response content: {r.content}")
            return False

        with open(filename, "wb") as f:
            f.write(r.content)

        return True


